#!/bin/bash

# mplayer-lastfm (lmplayer) is part of http://code.google.com/p/camtools,
# copyright 2007 Camille Huot,
# and is licensed under http://www.gnu.org/copyleft/gpl.html

# lmplayer is a wrapper to mplayer that sends information about your music
# files played to last.fm. it's scrobbling.

# WARNING: to use it, you need lastfmsubmitd
# -> http://www.red-bean.com/~decklin/software/lastfmsubmitd/
# . Grab the .tar.bz2 and untar it
# . To install it as a user:
#   python setup.py install --home $HOME
# . Configure it, ~/.lastfmsubmitd.conf:
#   [account]
#   user: cameuh
#   password: *********
# . Add "export PYTHONPATH=~/lib/python:$PYTHONPATH" in your ~/.bash_profile
# . Add "export PATH=~/bin:$PATH" in your ~/.bash_profile
# . source ~/.bash_profile
# . ln -s ~/lib/lastfmsubmitd/lastfmsubmit ~/bin/  (don't ask me why...)
# . Prepare some directories:
#   sudo mkdir /var/log/lastfm /var/spool/lastfm
#   sudo chown $(whoami) /var/log/lastfm /var/spool/lastfm
# . Run the daemon:
#   lastfmsubmitd
#   tail -f /var/log/lastfm/lastfm.log

# Now you can play files:
# lmplayer /media/audio/2006/Slayer-2006-Christ_Illusion/Slayer-04-Jihad.ogg

# WARNING: lmplayer relies on TAGS to gather information

Artist=0
Title=1
Album=2
Length=3
mplayer -quiet -identify $* | while read line; do
 if [ "${line:0:3}" != "ID_" ]; then
  echo "$line"
  continue
 fi
 if [ "${line:0:11}" = "ID_AUDIO_ID" ]; then
  unset My
  continue
 fi
 if [ "${line:0:9}" = "ID_LENGTH" ]; then
  My[Length]="$(echo $line | sed -e 's/^.*=//' -e 's/\..*$//')"
  continue
 fi
 if [ "${line:0:17}" = "ID_CLIP_INFO_NAME" ]; then
  NextIs="${line:19}"
  if [[ $NextIs == "Name" ]]; then NextIs=Title; fi
  if [ "$NextIs" != "Artist" -a "$NextIs" != "Title" -a "$NextIs" != "Album" ]; then
   NextIs=""
  fi
  continue
 fi
 if [ "${line:0:18}" = "ID_CLIP_INFO_VALUE" ]; then
  [ -z "$NextIs" ] && continue
  My[$NextIs]="${line:20}"
 fi
 if [ -n "${My[Title]}" -a -n "${My[Artist]}" -a -n "${My[Album]}" -a -n "${My[Length]}" ]; then
  lastfmsubmit --length "${My[Length]}" --artist "${My[Artist]}" --title "${My[Title]}" --album "${My[Album]}" --quiet
  unset My
 fi
done
